package com.kaede.popcake;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class KaedeShake {
	IShakeCallback ishake;
	private SensorManager mSensorManager; 
	private float mAccel;          // acceleration apart from gravity
    private float mAccelCurrent;   // current acceleration including gravity
    private float mAccelLast;      // last acceleration including gravity
    private int level=5;
    private final SensorEventListener mSensorListener = new SensorEventListener() {
        public void onSensorChanged(SensorEvent se) {
          float x = se.values[0];
          float y = se.values[1];
          float z = se.values[2];
          
          mAccelLast = mAccelCurrent;
          mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
          float delta = mAccelCurrent - mAccelLast;
          mAccel = mAccel * 0.9f + delta; // perform low-cut filter
         
          if(mAccel  > level){
             ishake.onShake();
          }else{
             ishake.onShakeIgnore();
          }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
	public KaedeShake(Context context,IShakeCallback ishake)
	{
		this.ishake=ishake;
		mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
	       
        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;
	}
	
	public void setLevel(int i)
	{
		this.level=i;
	}
	
	public interface IShakeCallback
	{
		public void onShake();
		public void onShakeIgnore();
	}
}
